﻿using ebMS3dotnet.Core.Configuration;
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel.Channels;
using System.ServiceModel.Dispatcher;
using System.Text;
using System.Threading.Tasks;

namespace ebMS3dotnet.Core
{
    class ebMS3Service : IService
    {
        async public Task<Message> ProcessMessage(Message message)
        {
            var filterTable = ebMS3ConfigurationSection.GetSection().CreateFilterTable();
            IOneWayProcessor processor;
            bool filterFound = filterTable.GetMatchingValue(message, out processor);
            if (!filterFound)
                throw new ArgumentException("A matching message filter was not found.");

            Task task = null;
           //For handling exceptions that occur synchronously.
            try
            {
                task = processor.ProcessMessage(message);
            }
            catch(Exception ex)
            {
                HandleProcessorException(processor.GetType().Name, ex);
            }
            Task<Message> task2 = task.ContinueWith<Message>((t) =>
                {
                    if (t.Exception == null)
                        return Message.CreateMessage(MessageVersion.Soap11, "");
                    throw HandleProcessorException(processor.GetType().Name, t.Exception);
                });
        
            return await task2;
        }

        private Exception HandleProcessorException(string processorType, Exception ex)
        {
            throw new ProcessorException(processorType, ex);
        }
    }
}
